﻿using System;
using System.Collections.Generic;
using System.Linq;

using Caliburn.Micro;

using Haushaltsbuch.Helpers;
using Haushaltsbuch.Helpers.Enums;

using Ninject.Extensions.Conventions.BindingGenerators;
using Ninject.Syntax;

namespace Haushaltsbuch.Extensions
{
    public class ExportBindingGenerator : IBindingGenerator
    {
        public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, IBindingRoot bindingRoot)
        {
            var attributes = type.GetAttributes<ExportAttribute>(true);
            foreach (var attribute in attributes)
            {
                var interfaceType = attribute.ServiceType;
                if (!interfaceType.IsAssignableFrom(type))
                {
                    throw new Exception("Falscher Typ in Export-Attribut.");
                }

                var bindingConfig = bindingRoot
                    .Bind(interfaceType)
                    .To(type);

                switch (attribute.Mode)
                {
                    case ExportMode.Singleton:
                        yield return (IBindingWhenInNamedWithOrOnSyntax<object>)bindingConfig.InSingletonScope();
                        break;
                    case ExportMode.Transient:
                        yield return (IBindingWhenInNamedWithOrOnSyntax<object>)bindingConfig.InTransientScope();
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }
        }
    }
}